import React, { PureComponent } from 'react';
import { Layout, Button, Row, Col, Checkbox, Form, Input } from 'antd';
import { WidthProvider, Responsive } from "react-grid-layout";
import _ from "lodash";
import ReactEcharts from 'echarts-for-react';
import { getBarChart, getLineChart, getPieChart } from "./chart";
import { getTitle, getImage, getText } from "./component";

const ResponsiveReactGridLayout = WidthProvider(Responsive);
const { Header, Content } = Layout;
// const handlefinish = (values) => {
//   debugger;
//   console.log('Success:',values);
// };

const widgets = [];

export default class DragLayout extends PureComponent {
  static defaultProps = {
    cols: { lg: 24, md: 20, sm: 12, xs: 8, xxs: 6 },
    rowHeight: 12,
  };

  success = (id) => {
    //const layouts = this.getFromLS("layouts") || {};
    this.state.layouts.xxs.map((item) => {
      if (item.i === id) {

      }
    });
    // debugger;
  }

  constructor(props) {
    super(props);

    this.state = {
      layouts: this.getFromLS("layouts") || {},
      widgets: [],
      initialValues: {},
    }
  }

  getFromLS(key) {
    let ls = {};
    if (global.localStorage) {
      try {
        ls = JSON.parse(global.localStorage.getItem("rgl-8")) || {};
      } catch (e) {
        /*Ignore*/
      }
    }
    return ls[key];
  }

  saveToLS(key, value) {
    if (global.localStorage) {
      global.localStorage.setItem(
        "rgl-8",
        JSON.stringify({
          [key]: value
        })
      );
    }
  }

  handlefinish = (values) => {
    console.log('Success:', widgets);
  };


  generateDOM = () => {
    return _.map(this.state.widgets, (l, i) => {
      let option;
      // if (l.type === 'bar') {
      //   option = getBarChart();
      // }else if (l.type === 'line') {
      //   option = getLineChart();
      // }else if (l.type === 'pie') {
      //   option = getPieChart();
      // }
      let component = null;

      if (l.type === 'line') {
        option = getLineChart();
        component = (
          <ReactEcharts
            option={option}
            notMerge={true}
            lazyUpdate={true}
            style={{ width: '100%', height: '100%' }}
          />
        )
      }

      try {
        const h = JSON.parse(global.localStorage.getItem("rgl-8")).layouts.lg[i].h;
        //console.log(l.h, h);
        l.h = h;
      } catch (error) {
      }


      if (l.type === 'title') {
        option = getTitle(l, this.success);
      } else if (l.type === 'image') {
        option = getImage(l, this.success);
      } else if (l.type === 'text') {
        option = getText(l, this.success);
      }

      component = (option)

      return (
        <div key={l.i} data-grid={l}>
          <span className='remove' onClick={this.onRemoveItem.bind(this, i)}>x</span>
          {component}
        </div>
      );
    });
  };

  addChart(type) {
    const addItem = {
      x: (this.state.widgets.length * 3) % (this.state.cols || 12),
      y: Infinity, // puts it at the bottom
      w: 3,
      h: 2,
      i: new Date().getTime().toString(),
    };
    this.setState(
      {
        widgets: this.state.widgets.concat({
          ...addItem,
          type,
        }),
      },
    );

    widgets.push(addItem)
  };

  onRemoveItem(i) {
    console.log(this.state.widgets)
    this.setState({
      widgets: this.state.widgets.filter((item, index) => index !== i)
    });
    const res = widgets.filter((item, index) => index !== i)
    this.updateWidgets(res);
  }

  updateWidgets(newWidgets) {
    //this.state.layouts.xxs
    widgets.splice(0, widgets.length);
    widgets.push(...newWidgets);
  }

  onLayoutChange(layout, layouts) {
    this.saveToLS("layouts", layouts);
    this.setState({ layouts });
    this.updateWidgets(layouts.xxs);
  }

  render() {
    return (
      <Layout>
        <Header style={{ position: 'fixed', zIndex: 1, width: '100%', 'padding': '0 30px' }}>
          <Button type="primary" style={{ 'marginRight': '7px' }} onClick={this.addChart.bind(this, 'title')}>添加标题</Button>
          <Button type="primary" style={{ 'marginRight': '7px' }} onClick={this.addChart.bind(this, 'image')}>添加图片</Button>
          <Button type="primary" style={{ 'marginRight': '7px' }} onClick={this.addChart.bind(this, 'text')}>添加文本</Button>
        </Header>
        <Content style={{ marginTop: 80 }}>
          <Row>
            <Col span={12}>
              <Form
                name="basic"
                labelCol={{
                  span: 8,
                }}
                wrapperCol={{
                  span: 16,
                }}
                style={{
                  maxWidth: 600,
                }}
                autoComplete="off"
              >
                <Form.Item
                  label="Username"
                  name="username"
                  rules={[
                    {
                      required: true,
                      message: 'Please input your username!',
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  wrapperCol={{
                    offset: 8,
                    span: 16,
                  }}
                >
                  <Button type="primary" htmlType="submit" onClick={this.handlefinish}>
                    Submit
                  </Button>
                </Form.Item>
              </Form>
            </Col>
            <Col span={12}>
              <div style={{ background: '#fff', minHeight: 812, width: 375, border: '2px solid' }}>
                <ResponsiveReactGridLayout
                  className="layout"
                  {...this.props}
                  layouts={this.state.layouts}
                  onLayoutChange={(layout, layouts) =>
                    this.onLayoutChange(layout, layouts)
                  }
                >
                  {this.generateDOM()}
                </ResponsiveReactGridLayout>
              </div>
            </Col>
          </Row>
        </Content>
      </Layout>
    )
  }
}
